package com.pallass.common.jpa.domain;

import java.util.Iterator;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

/**
 * Specification(条件列表) in the sense of Domain Driven Design.
 * 
 * @author Houor
 * 
 * @createTime: 2017-02-23 09:20
 *
 */
public class ListSpecification<T> implements Specification<T> {

	/**
	 * 条件列表
	 */
	List<SpecificationItem> itemList;

	public ListSpecification(List<SpecificationItem> itemList) {
		this.itemList = itemList;
	}
	
	

	/* 
	 * 创建Where子句
	 * 
	 * @see org.springframework.data.jpa.domain.Specification
	 */
	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
		Predicate result = null;
		if (itemList == null || itemList.isEmpty()) {
			return result;
		}
		Iterator<SpecificationItem> itemIterator = itemList.iterator();
		result = itemIterator.next().generateOperatorPredicate(root, criteriaBuilder);
		result = criteriaBuilder.and(result);
		while (itemIterator.hasNext()) {
			SpecificationItem item = itemIterator.next();
			Predicate temp = item.generateOperatorPredicate(root, criteriaBuilder);
			if (temp != null) {
				result = item.generateCompositionPredicate(criteriaBuilder, result, temp);
			}
		}

		return result;
	}

}
